package com.webdev.base.config;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.webdev.base.pojo.Admin;
import com.webdev.base.service.IAdminService;
import com.webdev.base.util.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Configuration
@Slf4j
public class AdminArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IAdminService adminService;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        return parameterType == Admin.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        if (request == null) return null;
        String token = request.getHeader("token");
        if (token == null) return null;
        try {
            TokenUtils.verifyToken(token);
        } catch (JWTVerificationException e) {
            log.info("token验证错误" + token);
            return null;
        }
        return adminService.getUserByToken(token);
    }
}
